package com.talent.service.impl;

import com.talent.handler.BaseException;
import com.talent.mapper.NoticeBannerMapper;
import com.talent.mapper.NoticeMapper;
import com.talent.pojo.entity.Notice;
import com.talent.pojo.entity.NoticeBanner;
import com.talent.service.NoticeBannerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 公告轮播服务实现类
 */
@Service
@Slf4j
public class NoticeBannerServiceImpl implements NoticeBannerService {

    @Autowired
    private NoticeBannerMapper noticeBannerMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 获取所有轮播列表（按排序顺序）
     * 实时从notice表获取标题和发布时间
     */
    @Override
    public List<NoticeBanner> getList() {
        List<NoticeBanner> banners = noticeBannerMapper.selectAll();
        
        // 遍历轮播列表，从notice表实时获取标题和发布时间
        for (NoticeBanner banner : banners) {
            Notice notice = noticeMapper.getById(banner.getNoticeId());
            if (notice != null) {
                banner.setNoticeTitle(notice.getTitle());
                banner.setPublishTime(notice.getPublishTime());
                banner.setNoticeLink(notice.getLinkUrl());
                banner.setNoticeType(notice.getType());
            } else {
                // 如果公告已被删除，标记为已删除
                banner.setNoticeTitle("[公告已删除]");
                banner.setPublishTime(null);
                banner.setNoticeLink(null);
                banner.setNoticeType(null);
            }
        }
        
        return banners;
    }


    /**
     * 获取所有轮播列表（按排序顺序）
     * 实时从notice表获取标题和发布时间
     */
    @Override
    public List<NoticeBanner> getWechatList() {
        List<NoticeBanner> banners = noticeBannerMapper.selectWechatAll();

        // 遍历轮播列表，从notice表实时获取标题和发布时间
        for (NoticeBanner banner : banners) {
            Notice notice = noticeMapper.getById(banner.getNoticeId());
            if (notice != null) {
                banner.setNoticeTitle(notice.getTitle());
                banner.setPublishTime(notice.getPublishTime());
                banner.setNoticeLink(notice.getLinkUrl());
                banner.setNoticeType(notice.getType());
            } else {
                // 如果公告已被删除，标记为已删除
                banner.setNoticeTitle("[公告已删除]");
                banner.setPublishTime(null);
                banner.setNoticeLink(null);
                banner.setNoticeType(null);
            }
        }

        return banners;
    }

    /**
     * 批量添加轮播公告
     */
    @Override
    @Transactional
    public void batchAdd(List<Long> noticeIds) {
        if (noticeIds == null || noticeIds.isEmpty()) {
            throw new BaseException("公告ID列表不能为空");
        }

        // 获取当前最大排序值
        Integer maxSortOrder = noticeBannerMapper.selectMaxSortOrder();
        if (maxSortOrder == null) {
            maxSortOrder = 0;
        }

        List<NoticeBanner> noticeBanners = new ArrayList<>();
        for (int i = 0; i < noticeIds.size(); i++) {
            Long noticeId = noticeIds.get(i);

            // 检查是否已存在
            NoticeBanner existBanner = noticeBannerMapper.selectByNoticeId(noticeId);
            if (existBanner != null) {
                log.warn("公告ID {}已在轮播中，跳过", noticeId);
                continue;
            }

            // 查询公告信息
            Notice notice = noticeMapper.getById(noticeId);
            if (notice == null) {
                log.warn("公告ID {}不存在，跳过", noticeId);
                continue;
            }

            // 创建轮播记录
            NoticeBanner noticeBanner = new NoticeBanner();
            noticeBanner.setNoticeId(noticeId);
            noticeBanner.setSortOrder(maxSortOrder + i + 1);
            noticeBanner.setStatus(1); // 默认启用
            noticeBanner.setCreateTime(LocalDateTime.now());
            noticeBanner.setUpdateTime(LocalDateTime.now());

            noticeBanners.add(noticeBanner);
        }

        if (!noticeBanners.isEmpty()) {
            noticeBannerMapper.batchInsert(noticeBanners);
            log.info("成功添加{}条轮播公告", noticeBanners.size());
        }
    }

    /**
     * 根据ID删除轮播公告
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        NoticeBanner noticeBanner = noticeBannerMapper.selectById(id);
        if (noticeBanner == null) {
            throw new BaseException("轮播公告不存在");
        }

        noticeBannerMapper.deleteById(id);
        log.info("删除轮播公告：id={}", id);

        // 重新调整排序
        reorderBanners();
    }

    /**
     * 更新轮播状态
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        NoticeBanner noticeBanner = noticeBannerMapper.selectById(id);
        if (noticeBanner == null) {
            throw new BaseException("轮播公告不存在");
        }

        if (status != 0 && status != 1) {
            throw new BaseException("状态值无效");
        }

        noticeBannerMapper.updateStatus(id, status);
        log.info("更新轮播公告状态：id={}, status={}", id, status);
    }

    /**
     * 交换两个轮播的排序顺序
     */
    @Override
    @Transactional
    public void swapSort(Long id1, Long id2) {
        NoticeBanner banner1 = noticeBannerMapper.selectById(id1);
        NoticeBanner banner2 = noticeBannerMapper.selectById(id2);

        if (banner1 == null || banner2 == null) {
            throw new BaseException("轮播公告不存在");
        }

        // 交换排序值
        Integer tempSort = banner1.getSortOrder();
        noticeBannerMapper.updateSortOrder(id1, banner2.getSortOrder());
        noticeBannerMapper.updateSortOrder(id2, tempSort);

        log.info("交换轮播公告排序：id1={}, id2={}", id1, id2);
    }

    /**
     * 重新调整所有轮播的排序顺序（从1开始连续）
     */
    private void reorderBanners() {
        List<NoticeBanner> banners = noticeBannerMapper.selectAll();
        for (int i = 0; i < banners.size(); i++) {
            NoticeBanner banner = banners.get(i);
            if (banner.getSortOrder() != i + 1) {
                noticeBannerMapper.updateSortOrder(banner.getId(), i + 1);
            }
        }
    }
}
